
#include <iostream>
#include <sys/types.h> 
#include <sys/socket.h>
#include <string>
#include <sstream>
#include <iostream>
#include<string.h>
#include <netinet/in.h> 
#include <arpa/inet.h>
#include <unistd.h>
#include "Log.hpp"

using namespace LogModule;

// ./client ip port
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        std::cerr << "格式错误,正确的格式为: " << "./client ip port" <<std::endl;
        exit(1);
    }
    Enable_Console_Log_Strategy();
    std::string ServerIp = argv[1];
    uint16_t ServerPort = std::stoi(argv[2]);

    // 1.创建套接字
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        std::cerr << "创建套接字失败" << std::endl;
        exit(2);
    }
    // 2.发送到服务器
    struct sockaddr_in sock;
    
    sock.sin_family = AF_INET;
    sock.sin_port = htons(ServerPort);  //端口号转换字节序
    inet_pton(AF_INET,ServerIp.c_str(),&sock.sin_addr); //IP地址转换
    
    // 连接服务器
    if(connect(sockfd,(struct sockaddr*)&sock,sizeof(sock)) == -1)
    {
        std::cerr << "连接服务器失败" << std::endl;
        exit(3);
    }
    while(true)
    {
        std::string input;
        getline(std::cin,input);
        write(sockfd,input.c_str(),input.size());

        // 3.接收服务器发过来的内容
        char buff[1024];
        read(sockfd,buff,sizeof(buff));
        LOG(LogLevel::INFO) << buff;
        memset(buff,0,sizeof(buff));


    }
   

    

    return 0;
}